USE GESTION2
go
IF OBJECT_ID('dbo.WASP_D0005_RENTAS') IS NOT NULL
BEGIN
    DROP PROCEDURE dbo.WASP_D0005_RENTAS
    IF OBJECT_ID('dbo.WASP_D0005_RENTAS') IS NOT NULL
        PRINT '<<< FAILED DROPPING PROCEDURE dbo.WASP_D0005_RENTAS >>>'
    ELSE
        PRINT '<<< DROPPED PROCEDURE dbo.WASP_D0005_RENTAS >>>'
END
go
SET ANSI_NULLS ON
go
SET QUOTED_IDENTIFIER ON
go
CREATE PROCEDURE WASP_D0005_RENTAS
AS

BEGIN
select z07375ct2, max(z07375fan)  as z07375fan
into #temp
from z07375  (nolock) group by z07375ct2

select b.z07375ct2, b.z07375fan, max(z07375fme)  as z07375fme
into #temp_2
from z07375 as a (nolock), #temp as b
where a.z07375ct2 = b.z07375ct2  and 
      a.z07375fan = b.z07375fan
group by b.z07375ct2, b.z07375fan



select  distinct b.z07375ct2 as cta, a.z07375imp importe, f.ctccli as tipo 
into #rentas
from z07375 as a (nolock), #temp_2 as b, fsd008 f (nolock)
where  a.z07375ct2 = b.z07375ct2 and
       a.z07375fan = b.z07375fan and 
       a.z07375fme = b.z07375fme and
       a.z07375ct2 = f.ctnro
union
select Z07378CT2 as cta, Z07378BRU as importe, ctccli as tipo
from z07378  (nolock), fsd008 (nolock)
where Z07378CT2 = ctnro

select cta, tipo, sum(cast(importe as numeric)) as importe
into dbo.mt_rentas
from #rentas
group by cta, tipo

drop table #temp

drop table #temp_2

drop table #rentas
END
go
SET ANSI_NULLS OFF
go
SET QUOTED_IDENTIFIER OFF
go
IF OBJECT_ID('dbo.WASP_D0005_RENTAS') IS NOT NULL
    PRINT '<<< CREATED PROCEDURE dbo.WASP_D0005_RENTAS >>>'
ELSE
    PRINT '<<< FAILED CREATING PROCEDURE dbo.WASP_D0005_RENTAS >>>'
go
